package edu.hcnu.service;

import edu.hcnu.entity.Car;
import edu.hcnu.entity.CarRecord;
import edu.hcnu.mapper.CarMapper;
import edu.hcnu.mapper.TickerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: Administrator
 * @time: 2023/4/29 18:09
 */
@Service
public class TicketService {

    @Autowired
    private TickerMapper mapper;

    @Autowired
    private CarMapper carMapper;

    @Cacheable(cacheNames = "query",key = "#cid")
    public String query(String cid) {
        // 查询是否有这个车次
        if(carMapper.isExists(cid)==null){
            return  "没有这个车次";
        }
        return String.valueOf(mapper.querySeat(cid) - mapper.queryHasBuy(cid));
    }


    @Caching(evict = {
            // 清除车次余量缓存
            @CacheEvict(cacheNames = "query",key = "#cid"),
            // 清除我的购票记录缓存
            @CacheEvict(cacheNames = "queryMyTicketInfo",key = "#uid"),
            @CacheEvict(cacheNames = "getAllTicket")


    })
    public synchronized String buy(String cid, String uid) {

        // 查询是否有这个车次
        if(carMapper.isExists(cid)==null){
            return  "没有这个车次";
        }

        // 表示还有余票可以购买
        if (mapper.querySeat(cid) - mapper.queryHasBuy(cid) > 0) {
            // 本人已经买过票就不给再买一次同一车次的了
            if (mapper.queryHasRecord(uid, cid) != null) {
                return "您已经购买过该车次";
            }
            mapper.insertRecord(uid, cid);
            return "success";
        }
        return "没有余票";
    }

    @Caching(evict = {
            // 清除车次余量缓存
            @CacheEvict(cacheNames = "query",key = "#cid"),
            // 清除我的购票记录缓存
            @CacheEvict(cacheNames = "queryMyTicketInfo",key = "#uid"),
            @CacheEvict(cacheNames = "getAllTicket")

    })
    public boolean delete(String cid, String uid) {
        // 本人已经买过票才能退票
        if (mapper.queryHasRecord(uid, cid) != null) {
            return mapper.deleteRecord(uid, cid);
        }
        return false;

    }
@Cacheable(cacheNames = "queryMyTicketInfo")
    public List<Car> queryMyTicketInfo(String uid) {
        List<CarRecord> records=mapper.queryByUID(uid);

        List<String> ids=new ArrayList<>();

        for (CarRecord record : records) {
            ids.add(record.getCid());
        }

        if(ids.size()==0){
            return null;
        }

      return  carMapper.queryBatchIds(ids);
    }

    @Cacheable(cacheNames = "getAllTicket")
    public List<CarRecord> getAll() {
        return  mapper.getAllTicket();
    }
}
